import React from 'react';
import PropTypes from 'prop-types';
import EditDialog from './editDialog';

export default class ProjectModal extends React.Component {
  static propTypes = {
    trigger: PropTypes.element,
    closeModal: PropTypes.func,
  };

  static defaultProps = {
    trigger: null,
    closeModal: () => {},
  };

  constructor(props) {
    super(props);
    this.state = {
      isModalOpen: false,
    };
  }

  static getDerivedStateFromProps(props) {
    if (props.trigger) {
      return {};
    }
    return {
      isModalOpen: props.isModalOpen,
    };
  }

  showModal = () => {
    this.setState({
      isModalOpen: true,
    });
  };

  closeModal = () => {
    this.setState({
      isModalOpen: false,
    });
  };

  render() {
    return (
      <React.Fragment>
        {this.state.isModalOpen ? (
          <EditDialog {...this.props} closeModal={this.closeModal} />
        ) : null}
        {!!this.props.trigger &&
          React.cloneElement(this.props.trigger, { onClick: this.showModal })}
      </React.Fragment>
    );
  }
}
